package com.hlk.admin.controller;

import com.hlk.admin.service.AdminUserService;
import com.hlk.constant.Constant;
import com.hlk.admin.AdminControllerApi;
import com.hlk.enums.ResponseStatusEnum;
import com.hlk.exception.HuaException;
import com.hlk.pojo.AdminUser;
import com.hlk.pojo.bo.AdminLoginBO;
import com.hlk.pojo.bo.NewAdminBO;
import com.hlk.result.Result;
import com.hlk.utils.CookieUtils;
import com.hlk.utils.PageResult;
import com.hlk.utils.ValidateUtils;
import com.hlk.utils.redis.RedisKeys;
import com.hlk.utils.redis.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * @author hlk
 * @version 1.0
 * @date 2020-12-23 8:48
 */
@RestController
public class AdminController implements AdminControllerApi {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private CookieUtils cookieUtils;
    @Autowired
    private AdminUserService adminUserService;

    @Override
    public Result adminLogin(AdminLoginBO adminLoginBO, HttpServletRequest request, HttpServletResponse response, BindingResult result) {
        // 校验参数是否符合
        if (result.hasErrors()) {
            Map<String, String> map = ValidateUtils.checkParams(result);
            return Result.errorMap(map);
        }

        // 查询用户
        AdminUser adminUser = adminUserService.selectByUsername(adminLoginBO.getUsername());
        if (adminUser == null) {
            return Result.errorCustom(ResponseStatusEnum.ADMIN_NOT_EXIT_ERROR);
        }

        // 校验密码是否正确
        boolean isPwdMatch = BCrypt.checkpw(adminLoginBO.getPassword(), adminUser.getPassword());
        if (isPwdMatch) {
            doLoginSettings(adminUser, response);
            return Result.ok();
        } else {
            return Result.errorCustom(ResponseStatusEnum.ADMIN_NOT_EXIT_ERROR);
        }
    }

    /**
     * 用于admin用户登录过后的基本信息设置
     *
     * @param admin
     * @param response
     */
    private void doLoginSettings(AdminUser admin,
                                 HttpServletResponse response) {
        // 保存token放入到redis中
        String token = UUID.randomUUID().toString();
        redisUtils.set(RedisKeys.getAdminTokenKey(admin.getId()), token);

        // 保存admin登录基本token信息到cookie中
        cookieUtils.setCookie(response, "atoken", token, CookieUtils.COOKIE_MONTH);
        cookieUtils.setCookie(response, "aid", admin.getId(), CookieUtils.COOKIE_MONTH);
        cookieUtils.setCookie(response, "aname", admin.getAdminName(), CookieUtils.COOKIE_MONTH);
    }

    @Override
    public Result adminIsExist(String username) {
        CheckAdminUserName(username);
        return Result.ok();
    }

    /**
     * 校验admin的用户名是否已经存在
     *
     * @param username
     */
    private void CheckAdminUserName(String username) {
        AdminUser adminUser = adminUserService.selectByUsername(username);
        if (adminUser != null) {
            throw new HuaException(ResponseStatusEnum.ADMIN_USERNAME_EXIST_ERROR);
        }
    }

    @Override
    public Result addNewAdmin(NewAdminBO newAdminBO, HttpServletRequest request, HttpServletResponse response, BindingResult result) {
        // 校验参数是否符合
        if (result.hasErrors()) {
            Map<String, String> map = ValidateUtils.checkParams(result);
            return Result.errorMap(map);
        }

        // 如果人脸登录图为空，则校验密码不能为空
        if (StringUtils.isNotBlank(newAdminBO.getImg64())) {
            if (StringUtils.isBlank(newAdminBO.getPassword()) || StringUtils.isBlank(newAdminBO.getConfirmPassword())) {
                return Result.errorCustom(ResponseStatusEnum.ADMIN_PASSWORD_NULL_ERROR);
            }
        }

        // 校验两次密码是否一致
        if (!newAdminBO.getPassword().equalsIgnoreCase(newAdminBO.getConfirmPassword())) {
            throw new HuaException(ResponseStatusEnum.ADMIN_PASSWORD_ERROR);
        }

        // 校验用户名是否唯一
        CheckAdminUserName(newAdminBO.getUsername());
        adminUserService.insertNewAdmin(newAdminBO);
        return Result.ok();
    }

    @Override
    public Result getAdminList(Integer page, Integer pageSize) {
        if (page == null) {
            page = Constant.PAGE;
        }

        if (pageSize == null) {
            pageSize = Constant.PAGESIZE;
        }

        PageResult result = adminUserService.selectAdminUserByPage(page, pageSize);
        return Result.ok(result);
    }

    @Override
    public Result adminLogout(String adminId, HttpServletRequest request, HttpServletResponse response) {
        // 从redis中删除admin的会话token
        redisUtils.del(RedisKeys.getAdminTokenKey(adminId));

        // 从cookie中清理adming登录的相关信息
        cookieUtils.deleteCookie(response, "atoken");
        cookieUtils.deleteCookie(response, "aid");
        cookieUtils.deleteCookie(response, "aname");

        return Result.ok();
    }
}
